package impl

import (
	"adam2/internal/constants"
	"adam2/internal/domain"
	"adam2/internal/model"
	"adam2/internal/properties"
	"anubis-framework/pkg/io"
	"anubis-framework/pkg/ui"
	"anubis-framework/pkg/util"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/bournex/ordered_container"
	"os/exec"
	"time"
)

type CommodityFutureMinuteDataServiceImpl struct {
	*BaseServiceImpl
}

func GetCommodityFutureMinuteDataServiceImpl() *CommodityFutureMinuteDataServiceImpl {
	return &CommodityFutureMinuteDataServiceImpl{GetBaseServiceImpl()}
}

// 监视直线上涨或直线下跌的行情
func (_commodityFutureMinuteDataServiceImpl CommodityFutureMinuteDataServiceImpl) WatchStraightLineIncreaseOrDecreaseInCommodityFutureMinuteData(commodityFutureInfoArray model.CommodityFutureInfoArray) {
	io.Infoln("监控期货的开始时间：" + time.Now().Format("2006-01-02 15:04:05"))

	for _, commodityFutureInfo := range commodityFutureInfoArray {
		// 调用 Python 脚本
		cmd := exec.Command("python", properties.PythonProperties_.ManagePath, properties.PythonProperties_.PackageName, properties.PythonProperties_.WatchCommodityFutureMinuteDataMethodName, commodityFutureInfo.Code+"0")
		//cmd := exec.Command("python", domain.PythonConfig_.PythonManagePath, "api", "find_by_code", code+"0")

		// 捕获标准输出
		var out bytes.Buffer
		cmd.Stdout = &out

		// 运行命令并处理错误
		if err := cmd.Run(); err != nil {
			io.Infoln("调用python程序，获取期货[%s]时报错：", commodityFutureInfo.Code, err)
			continue
		}

		// 解析返回的 JSON 数据
		var orderMap ordered_container.OrderedMap
		if len(out.Bytes()) != 0 {
			if err := json.Unmarshal(out.Bytes(), &orderMap); err != nil {
				io.Infoln("解析json报错：", err)
				continue
			}
		} else {
			io.Infoln("调用python程序，获取期货[%s]的数据为空", commodityFutureInfo.Code)
			// 终止当前协程
			//_, cancel := context.WithCancel(context.Background())
			//cancel()
			continue
		}

		// 输出结果
		var datetimeArray = orderMap.Values[0].Value.(ordered_container.OrderedMap).Values
		var openArray = orderMap.Values[1].Value.(ordered_container.OrderedMap).Values
		var highArray = orderMap.Values[2].Value.(ordered_container.OrderedMap).Values
		var lowArray = orderMap.Values[3].Value.(ordered_container.OrderedMap).Values
		var closeArray = orderMap.Values[4].Value.(ordered_container.OrderedMap).Values
		var volumeArray = orderMap.Values[5].Value.(ordered_container.OrderedMap).Values
		var holdArray = orderMap.Values[6].Value.(ordered_container.OrderedMap).Values

		var _datetimeArray []string = make([]string, len(datetimeArray))
		var _openArray []float64 = make([]float64, len(openArray))
		var _highArray []float64 = make([]float64, len(highArray))
		var _lowArray []float64 = make([]float64, len(lowArray))
		var _closeArray []float64 = make([]float64, len(closeArray))
		var _volumeArray []int64 = make([]int64, len(volumeArray))
		var _holdArray []int64 = make([]int64, len(holdArray))

		for i := 0; i < len(datetimeArray); i++ {
			_datetimeArray[i] = datetimeArray[i].Value.(string)
		}
		for i := 0; i < len(openArray); i++ {
			_openArray[i], _ = openArray[i].Value.(json.Number).Float64()
		}
		for i := 0; i < len(highArray); i++ {
			_highArray[i], _ = highArray[i].Value.(json.Number).Float64()
		}
		for i := 0; i < len(lowArray); i++ {
			_lowArray[i], _ = lowArray[i].Value.(json.Number).Float64()
		}
		for i := 0; i < len(closeArray); i++ {
			_closeArray[i], _ = closeArray[i].Value.(json.Number).Float64()
		}
		for i := 0; i < len(volumeArray); i++ {
			_volumeArray[i], _ = volumeArray[i].Value.(json.Number).Int64()
		}
		for i := 0; i < len(holdArray); i++ {
			_holdArray[i], _ = holdArray[i].Value.(json.Number).Int64()
		}

		if (util.StringToDateTime(_datetimeArray[len(_datetimeArray)-1]).Minute() - util.StringToDateTime(_datetimeArray[len(_datetimeArray)-2]).Minute()) > 1 {
			var message string = fmt.Sprintf("期货[%s]的一分钟级别收盘价，最近的时间是[%s]，上一个时间是[%s]，超过了1分钟，存在异常，不再监控",
				commodityFutureInfo.Code, _datetimeArray[len(_datetimeArray)-1], _datetimeArray[len(_datetimeArray)-2])
			io.Infoln(message)
			continue
		}

		// 监控期货直线上涨或下跌
		if properties.PythonProperties_.WatchCommodityFutureMinuteDataStraightLineIncreaseDecreaseEnable {
			var currentClosePrice float64 = _closeArray[len(_closeArray)-1]
			var fiveMinutesEarlyClosePrice float64 = _closeArray[len(_closeArray)-6]
			if currentClosePrice > fiveMinutesEarlyClosePrice {
				var risePercentage float64 = (currentClosePrice - fiveMinutesEarlyClosePrice) / fiveMinutesEarlyClosePrice * 100
				if risePercentage >= properties.PythonProperties_.WatchCommodityFutureMinuteDataRiseOrFallThreshold {
					var currentTime time.Time = time.Now()
					var message string = fmt.Sprintf("当前时间[%s]，期货[%s %s]当前收盘价为[%f]，五分钟之前的收盘价为[%f]，上涨百分比为[%f]，超过了阈值[%f]",
						util.DateTimeToString(currentTime), commodityFutureInfo.Code, commodityFutureInfo.Name, currentClosePrice, fiveMinutesEarlyClosePrice, risePercentage, properties.PythonProperties_.WatchCommodityFutureMinuteDataRiseOrFallThreshold)
					io.Infoln(message)

					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableMessageBox {
						// 弹出提示对话框
						ui.MessageBox(message, "快速上涨")
					}
					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSoundAudio {
						// 播放报警音频
						domain.Manager_.AudioManager_.Sound(properties.PythonProperties_.WatchCommodityFutureMinuteDataAudioFilePath)
					}
					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSaveInDatabase {
						// 添加记录
						var straightLineIncreaseDecrease model.StraightLineIncreaseDecrease = model.StraightLineIncreaseDecrease{}
						straightLineIncreaseDecrease.Code = commodityFutureInfo.Code
						straightLineIncreaseDecrease.TransactionType = constants.COMMODITY_FUTURE
						straightLineIncreaseDecrease.Name = commodityFutureInfo.Name
						straightLineIncreaseDecrease.Message = message
						straightLineIncreaseDecrease.CreateTime = currentTime
						_commodityFutureMinuteDataServiceImpl.BaseServiceImpl._straightLineIncreaseDecreaseDaoImpl.Add(&straightLineIncreaseDecrease)
					}
				}
			}
			if currentClosePrice < fiveMinutesEarlyClosePrice {
				var fallPercentage float64 = (currentClosePrice - fiveMinutesEarlyClosePrice) / fiveMinutesEarlyClosePrice * 100
				if fallPercentage <= -properties.PythonProperties_.WatchCommodityFutureMinuteDataRiseOrFallThreshold {
					var currentTime time.Time = time.Now()
					var message string = fmt.Sprintf("当前时间[%s]，期货[%s %s]当前收盘价为[%f]，五分钟之前的收盘价为[%f]，下跌百分比为[%f]，超过了阈值[-%f]",
						util.DateTimeToString(currentTime), commodityFutureInfo.Code, commodityFutureInfo.Name, currentClosePrice, fiveMinutesEarlyClosePrice, fallPercentage, properties.PythonProperties_.WatchCommodityFutureMinuteDataRiseOrFallThreshold)
					io.Infoln(message)

					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableMessageBox {
						// 弹出提示对话框
						ui.MessageBox(message, "快速下跌")
					}
					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSoundAudio {
						// 播放报警音频
						domain.Manager_.AudioManager_.Sound(properties.PythonProperties_.WatchCommodityFutureMinuteDataAudioFilePath)
					}
					if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSaveInDatabase {
						// 添加记录
						var straightLineIncreaseDecrease model.StraightLineIncreaseDecrease = model.StraightLineIncreaseDecrease{}
						straightLineIncreaseDecrease.Code = commodityFutureInfo.Code
						straightLineIncreaseDecrease.TransactionType = constants.COMMODITY_FUTURE
						straightLineIncreaseDecrease.Name = commodityFutureInfo.Name
						straightLineIncreaseDecrease.Message = message
						straightLineIncreaseDecrease.CreateTime = currentTime
						_commodityFutureMinuteDataServiceImpl.BaseServiceImpl._straightLineIncreaseDecreaseDaoImpl.Add(&straightLineIncreaseDecrease)
					}
				}
			}
		}

		// 监控期货突破或跌破某一价位
		if properties.PythonProperties_.WatchCommodityFutureMinuteDataUpOrDownPriceEnable {
			var monitorCurrentPrice model.MonitorCurrentPrice
			monitorCurrentPrice.TransactionType = constants.COMMODITY_FUTURE
			monitorCurrentPrice.Available = constants.AVAILABLE
			monitorCurrentPrice.Code = commodityFutureInfo.Code
			var monitorCurrentPriceArray model.MonitorCurrentPriceArray = _commodityFutureMinuteDataServiceImpl.BaseServiceImpl._monitorCurrentPriceDaoImpl.Find(monitorCurrentPrice)
			if monitorCurrentPriceArray != nil && len(monitorCurrentPriceArray) > 0 {
				for _, monitorCurrentPrice := range monitorCurrentPriceArray {
					if monitorCurrentPrice.Code != commodityFutureInfo.Code {
						continue
					}

					var currentClosePrice float64 = _closeArray[len(_closeArray)-1]
					if monitorCurrentPrice.Comparison == constants.GREATER_THAN_OR_EQUAL &&
						monitorCurrentPrice.MonitorPrice >= currentClosePrice {

						var currentTime time.Time = time.Now()
						var message string = fmt.Sprintf("当前时间[%s]，期货[%s %s]当前收盘价为[%f]，向上突破了设置的价格[%f]",
							util.DateTimeToString(currentTime), commodityFutureInfo.Code, commodityFutureInfo.Name, currentClosePrice, monitorCurrentPrice.MonitorPrice)
						io.Infoln(message)

						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableMessageBox {
							// 弹出提示对话框
							ui.MessageBox(message, "向上突破")
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSoundAudio {
							// 播放报警音频
							domain.Manager_.AudioManager_.Sound(properties.PythonProperties_.WatchCommodityFutureMinuteDataAudioFilePath)
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSaveInDatabase {
							// 添加记录
							var straightLineIncreaseDecrease model.StraightLineIncreaseDecrease = model.StraightLineIncreaseDecrease{}
							straightLineIncreaseDecrease.Code = commodityFutureInfo.Code
							straightLineIncreaseDecrease.TransactionType = constants.COMMODITY_FUTURE
							straightLineIncreaseDecrease.Name = commodityFutureInfo.Name
							straightLineIncreaseDecrease.Message = message
							straightLineIncreaseDecrease.CreateTime = currentTime
							_commodityFutureMinuteDataServiceImpl.BaseServiceImpl._straightLineIncreaseDecreaseDaoImpl.Add(&straightLineIncreaseDecrease)
						}
					}
					if monitorCurrentPrice.Comparison == constants.LESS_THAN_OR_EQUAL &&
						monitorCurrentPrice.MonitorPrice <= currentClosePrice {

						var currentTime time.Time = time.Now()
						var message string = fmt.Sprintf("当前时间[%s]，期货[%s %s]当前收盘价为[%f]，向下跌破了设置的价格[%f]",
							util.DateTimeToString(currentTime), commodityFutureInfo.Code, commodityFutureInfo.Name, currentClosePrice, monitorCurrentPrice.MonitorPrice)
						io.Infoln(message)

						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableMessageBox {
							// 弹出提示对话框
							ui.MessageBox(message, "向下跌破")
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSoundAudio {
							// 播放报警音频
							domain.Manager_.AudioManager_.Sound(properties.PythonProperties_.WatchCommodityFutureMinuteDataAudioFilePath)
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSaveInDatabase {
							// 添加记录
							var straightLineIncreaseDecrease model.StraightLineIncreaseDecrease = model.StraightLineIncreaseDecrease{}
							straightLineIncreaseDecrease.Code = commodityFutureInfo.Code
							straightLineIncreaseDecrease.TransactionType = constants.COMMODITY_FUTURE
							straightLineIncreaseDecrease.Name = commodityFutureInfo.Name
							straightLineIncreaseDecrease.Message = message
							straightLineIncreaseDecrease.CreateTime = currentTime
							_commodityFutureMinuteDataServiceImpl.BaseServiceImpl._straightLineIncreaseDecreaseDaoImpl.Add(&straightLineIncreaseDecrease)
						}

						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableMessageBox {
							// 弹出提示对话框
							ui.MessageBox(message, "快速下跌")
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSoundAudio {
							// 播放报警音频
							domain.Manager_.AudioManager_.Sound(properties.PythonProperties_.WatchCommodityFutureMinuteDataAudioFilePath)
						}
						if properties.PythonProperties_.WatchCommodityFutureMinuteDataEnableSaveInDatabase {
							// 添加记录
							var straightLineIncreaseDecrease model.StraightLineIncreaseDecrease = model.StraightLineIncreaseDecrease{}
							straightLineIncreaseDecrease.Code = commodityFutureInfo.Code
							straightLineIncreaseDecrease.TransactionType = constants.COMMODITY_FUTURE
							straightLineIncreaseDecrease.Name = commodityFutureInfo.Name
							straightLineIncreaseDecrease.Message = message
							straightLineIncreaseDecrease.CreateTime = currentTime
							_commodityFutureMinuteDataServiceImpl.BaseServiceImpl._straightLineIncreaseDecreaseDaoImpl.Add(&straightLineIncreaseDecrease)
						}
					}
				}
			}
		}
	}
	io.Infoln("监控期货的结束时间：" + time.Now().Format("2006-01-02 15:04:05"))
}
